<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $helpers = array('Html', 'Form', 'Javascript','Time','Flash');
	var $uses = array('User', 'Subscriber');
	var $components = array('Email', 'Session','PasswordHelper');

	
//==========================================//

	function view()
	{
		$user = $this->Session->read('User');
		$id = $user['User']['id'];
		if (!$id) 
		{
			$this->Session->setFlash(__('No has iniciado Sesi&oacute;n.', true));
			$this->redirect(array('controller'=>'users','action'=>'login'));
		}
		
		$this->set('user', $this->User->read(null, $id));
	}
	
//==========================================//

	function add() 
	{
		if (!empty($this->data)) 
		{
		
			$datos= $this->User->findByEmail($this->data['User']['email']);
			if(!$datos['User'])
			{
			
				$this->User->create();
					$this->data['User']['activo']= 1;
					$this->data['User']['password'] = $this->PasswordHelper->generatePassword(8);
					
					
					
					$this->Subscriber->create();
				 	$this->data['Subscriber']['subscribers_name'] = $this->data['User']['nombres']." ". $this->data['User']['apellidos'];
					$this->data['Subscriber']['subscribers_email']  = $this->data['User']['email'];
					$this->data['Subscriber']['subscribers_user_id']=1;
					$this->Subscriber->save($this->data);
				
							
					
					if ($this->User->save($this->data)) 
					{
						$this->Session->setFlash(__('Se ha registrado satisfactoriamente', true));
						
						
						$this->Email->to = $this->data['User']['email'];//mail aqui
						$this->Email->replyTo = 'do-not-reply@publicidadyclasificados.com';
						$this->Email->from = 'Publicidad y Clasificados'.' <info@publicidadyclasificados.com>';
						$this->Email->subject = 'Publicidad y Clasificados, datos de ingreso';
					$mail =$this->data['User']['email'];
						//mail que se le envia al nuevo usuario
					$this->data['Contact']['message'] = 'Gracias por registrate en publicidadyclasificados.com, con estos datos puedes ingresar como usuario registrado y pautar con nosotros.';
					$this->data['Contact']['message'].= "\r\n".'Usuario: '.$mail;
					$this->data['Contact']['message'].= "\r\n".'Clave: '.$this->data['User']['password'];
					$this->data['Contact']['message'].= "\r\n".'Con estos datos pudes ingresar y cambiar tu clave.';
						
						if($this->Email->send($this->data['Contact']['message']))
						{
							$this->redirect(array('controller'=>'pages','action'=>'display','registration_succes'));
						}
						
					} 
					else 
					{
						$this->Session->setFlash(__('No se pudo guadar el usuario, por favor intente de nuevo.', true));
					}
			}
			
			else
			{
				$this->Session->setFlash(__('Ya se encuentra registrado en nuestra base de datos.', true));
			}
		}

	}


	
//==========================================//
	
	function activate_user( $email=  null ,$hash=null)
	{
		if(!$email || !$hash  )
		{
			$this->Session->setFlash('Debes haberte registrado');
			$this->redirect(array('/registro'));
			
		}
		
		$email = trim($email);
		$hash = trim($hash);
		
		if( $this->validate_email($email))
		{ 
			$datos = $this->User->findByEmail($email);	
			if($datos['User'] && !$datos['User']['activo'])
			{
				if($datos['User']['hash']==$hash)
				{
					$datos['User']['activo']=1;
					$this->data = $datos;
				
				
					if ($this->User->save($this->data)) 
					{
						$this->Session->setFlash(__('Se activo tu cuenta', true));
						$this->Session->write( 'User', $datos );
						$this->redirect(array('controller'=>'pages','action'=>'display','registration_succes'));
					}
				
				}
			}
			else
			{
				$this->Session->setFlash('Ya te encuentras registrado');
				$this->redirect(array('controller'=>'users','action'=>'add'));
			}		
		}
		else
		{
			$this->Session->setFlash('Direccion erronea');
			$this->redirect('/registro');
		}
		
	}
	
//==========================================//

	function recuperar_clave()
	{
		if(!empty($this->data))
		{
			$email = $this->data['User']['email'];
			$usuario =  $this->User->findByEmail($email);
			
			if($usuario['User'])
			{
				$this->Email->to = $usuario['User']['email'];//mail aqui
				$this->Email->replyTo = 'do-not-reply@publicidadyclasificados.com';
				$this->Email->from = 'Publicidad y Clasificados'.' <info@publicidadyclasificados.com>';
				$this->Email->subject = 'Te clave de publicidad y clasicados';
					
						//mail que se le envia al nuevo usuario
						$this->data['Contact']['message'] = 'Tu clave de publicidad y clasificados';
						$this->data['Contact']['message'].= "\r\n".'Usuario:'.$usuario['User']['email'];
			            $this->data['Contact']['message'].= "\r\n".'Clave:'.$usuario['User']['password'];
						
						if($this->Email->send($this->data['Contact']['message']))
						{
							$this->redirect(array('controller'=>'users','action'=>'login'));
						}
			}
		}
	}
	
	
//==========================================//	
	function login()
	{
	if(!empty($this->data))
	 {
		    $dbuser = $this->User->findByEmail($this->data['User']['email']);
			
			if($dbuser['User']['activo'])
			{
					if(!empty($dbuser) && ($dbuser['User']['password'] == $this->data['User']['password'] )) 
					{
					 
						$this->Session->write('User', $dbuser);
						$this->Session->setFlash('Se ha autenticado correctamente.');
						$this->redirect('/ver-mi-perfil');
					} 
					else 
					{
						$this->set('error', 'Su Nombre de usuario o clave son erradas.');
						$this->redirect('/login');
					}
        	}
			else
			{
				$this->Session->setFlash('Te encuentras registrado pero no has activado tu cuenta.');
			}
		}	
	
		
	}
	
	
//==========================================//	
	function logout() 
	{
	
	// delete the user session
	$this->Session->delete('User');
	// redirect to posts index page
	$this->Session->setFlash('Ha salido satisfactoriamente.');
	$this->redirect('/');
	
    }
	
	
//==========================================//
	function edit() {
		$datos =  $this->Session->read('User');
		$id = $datos['User']['id'];
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action'=>'view'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}

	
//==========================================//
	function admin_index() 
	{
		$this->layout = "admin";
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}
	
//==========================================//
	function admin_view($id = null) 
	{
		$this->layout = "admin";
		if (!$id) 
		{
				$this->Session->setFlash(__('Invalid User.', true));
				$this->redirect(array('action'=>'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}
	
	
//==========================================//
	function admin_add() 
	{
		$this->layout = "admin";
		if (!empty($this->data)) 
		{
			$this->User->create();
			if ($this->User->save($this->data)) 
			{
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action'=>'index'));
			}
			else 
			{
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
	}

	
//==========================================//
	function admin_edit($id = null) 
	{
	$this->layout = "admin";
		if (!$id && empty($this->data)) 
		{
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) 
		{
				if ($this->User->save($this->data)) 
				{
					$this->Session->setFlash(__('The User has been saved', true));
					$this->redirect(array('action'=>'index'));
				} 
				else 
				{
					$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) 
		{
			$this->data = $this->User->read(null, $id);
		}
	}
	
//==========================================//
	function admin_delete($id = null) {
		if (!$id) 
		{
			$this->Session->setFlash(__('Invalid id for User', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->del($id)) 
		{
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}
}
?>